<template>
  <div class="customer-contact-table-container">
    <el-table
      v-loading="listLoading"
      stripe
      :data="contactList"
      :highlight-current-row="false"
      header-row-class-name="common-list-table-header__v2"
      v-bind="extraAttrs"
    >
      <template slot="empty">
        <BaseListForNoData
          v-show="!listLoading"
          table-type="smallTable"
          :notice-msg="$t('common.base.tip.noData')"
        ></BaseListForNoData>
      </template>
      
      <el-table-column
        v-for="(column, index) in columns"
        v-if="column.show"
        :key="`${column.field}_${index}`"
        :label="column.label"
        :prop="column.field"
        :width="column.width"
        min-width="150px"
        :sortable="column.sortable"
        show-overflow-tooltip
        :align="column.align"
      >
        <template slot-scope="scope">
          <template v-if="column.field === 'state'">{{scope.row[column.field]}}</template>
          <template v-else-if="column.field === 'name'">
            <span class="custoemr-contact-name">
              <a
                v-if="allowEditLinkman"
                href="javascript:;"
                @click="openDialog(scope.row)"
                class="edit-btn"
                :class="scope.row.hasWechat || scope.row.canChat ? 'customer-linkman-name-wx' : ''"
              >{{scope.row[column.field]}}</a>
              <template v-else>{{scope.row[column.field]}}</template>
              <biz-wx-chat-button :user-id="scope.row.externalUserid" v-if="scope.row.canChat" />
              <ui-wx-tag v-else-if="scope.row.hasWechat" />
            </span>
          </template>
          <template v-else-if="column.field === 'from'">
            <el-tooltip
              class="item"
              effect="dark"
              :content="scope.row.esLinkManWXEntities.length>0?scope.row.esLinkManWXEntities[0].nickName:''"
              placement="right"
              v-if="scope.row.registeredSource===1"
            >
              <i class="iconfont icon-weixin1 color-green"></i>
            </el-tooltip>
          </template>
          <template v-else-if="column.field === 'phone'">
            <span class="align-items-center"> {{scope.row.phone}}
              <biz-call-icon :value="scope.row.phone" :sourceData="callCenterSourceData(scope)" />
            </span>
          </template>
          <div class="lm-action" v-else-if="column.field === 'action'">
            <el-dropdown class="dropdown" v-if="(allowEditLinkman && !scope.row.isMain && allowDeleteLinkman) || (scope.row.isMain && allowDeleteLinkman)">
              <span class="cur-point">
                {{$t('common.base.more')}}<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown" class="lang-select-dropdown">
                <el-dropdown-item v-if="scope.row.isMain" disabled>
                    <div>{{ $t('common.bizComponents.bizSendEmail.contactRadio.0') }}</div>
                </el-dropdown-item>
                <el-dropdown-item v-if="allowEditLinkman && !scope.row.isMain" :disabled="pending[scope.row.id]">
                  <div @click="setDefaultLinkman(scope.row)">{{$t('customer.detail.customerContactTable.setDefault')}}</div>
                </el-dropdown-item>
                <el-dropdown-item v-if="allowDeleteLinkman" :disabled="pending[scope.row.id]">
                  <div @click="deleteLinkman(scope.row)">{{$t('common.base.delete')}}</div>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <div v-else>
              <template>
                <span v-if="scope.row.isMain" style="line-height: 26px;padding: 1px">{{ $t('common.bizComponents.bizSendEmail.contactRadio.0') }}</span>
                <el-button
                  v-if="allowEditLinkman && !scope.row.isMain"
                  @click="setDefaultLinkman(scope.row)"
                  type="text"
                  :disabled="pending[scope.row.id]"
                >{{$t('customer.detail.customerContactTable.setDefault')}}</el-button>
              </template>
              <el-button
                v-if="allowDeleteLinkman"
                type="text"
                @click="deleteLinkman(scope.row)"
                :disabled="pending[scope.row.id]"
                class="delete-contact-btn"
                size="mini"
              >{{$t('common.base.delete')}}</el-button>
            </div>
          </div>

          <template v-else>{{scope.row[column.field]}}</template>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <BaseAddOnPagination :paginationInfo="paginationInfo" @pageJump="jump" @sizeChange="handleSizeChange" />

    <edit-contact-dialog
      ref="EditContactDialog"
      :customer="shareData.customer"
      :original-value="selectedContact"
      :is-phone-unique="shareData.isPhoneUnique"
      @submit-success="selectedContact = {}"
    ></edit-contact-dialog>
  </div>
</template>

<script>
import { formatDate } from 'pub-bbx-utils';
import platform from '@src/platform';
import EditContactDialog from '../operationDialog/EditContactDialog.vue';
import { getContactList } from '@src/api/CustomerContact.js';
import _ from 'lodash'
import { safeNewDate } from '@src/util/time';

export default {
  name: 'customer-contact-table',
  props: {
    shareData: {
      type: Object,
      default: () => ({})
    },
    initData: {
      type: Object,
      default: () => ({})
    },
    extraAttrs: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      pending: {},
      selectedContact: {},
      contactList: [],
      columns: [],
      paginationInfo: {
        pageSize: 10,
        pageNum: 1,
        totalItems: 0
      },
      listLoading: true
    };
  },
  computed: {
    customerId() {
      return this.shareData.customer ? this.shareData.customer.id : '';
    },
    allowEditCustomer() {
      return (
        !this.shareData.isDelete
        && !this.shareData.isDisable
      );
    },
    grayControler() {
      if (
        this.initData
        && (!this.initData.menus || this.initData.menus.length <= 0)
      ) {
        // 灰度开启 无公众号相关功能
        return true;
      }
      return false;
    },

    // 是否有编辑联系人权限
    allowEditLinkman() {
      return this.permission?.LINKMAN_EDIT
    },
    
    // 是否有删除联系人权限
    allowDeleteLinkman() {
      return this.permission?.LINKMAN_DELETE
    },

    /** 当前用户的权限 */
    permission() {
      return (this.initData.loginUser || {}).authorities
    },
  },
  mounted() {
    this.fetchData().then(() => {
      this.$emit('firstLoaded')
    })
    this.columns = this.buildColumns();
    this.$eventBus.$on(
      'customer_contact_table.update_linkman_list',
      this.fetchDataDelay
    );
  },
  beforeDestroy() {
    this.$eventBus.$off(
      'customer_contact_table.update_linkman_list',
      this.fetchDataDelay
    );
  },
  methods: {
    openDialog(contact) {
      if (!this.allowEditCustomer) return;
      this.selectedContact = contact;
      this.$nextTick(this.$refs.EditContactDialog.openDialog);
    },
    setDefaultLinkman(lm) {
      if (this.pending[lm.id]) return;
      this.pending[lm.id] = true;
      this.$http
        .post('/linkman/setMain', { id: lm.id }, false)
        .then(res => {
          if (res.status === 0) {
            this.fetchData();
          } else {
            platform.alert(res.message);
          }
          this.pending[lm.id] = false;
          this.$eventBus.$emit('customer_detail_view.update_customer_detail');
          this.fetchDataDelay()
        })
        .catch(err => console.error('err', err));
    },
    async deleteLinkman(lm) {
      if (lm.isMain) return platform.alert(this.$t('customer.detail.customerContactTable.deleteLinkman.canNot'));
      try {
        const res = await platform.confirm(this.$t('customer.detail.customerContactTable.deleteLinkman.confirmMsg'));
        if (!res) return;
        this.pending[lm.id] = true;
        const reqRes = await this.$http.post(
          '/linkman/delete',
          { ids: lm.id },
          false
        );
        delete this.pending[lm.id];
        if (reqRes.status === 0) {
          this.fetchData();
        } else {
          platform.alert(res.message);
        }
        this.$eventBus.$emit('customer_info_record.update_record_list');
        this.$eventBus.$emit('customer_detail_view.update_statistical_data');
        this.fetchDataDelay()
      } catch (e) {
        console.error('err');
      }
    },
    jump(pN) {
      this.paginationInfo.pageNum = pN;
      this.fetchData();
    },
    handleSizeChange(pageSize) {
      this.paginationInfo.pageSize = pageSize;
      this.paginationInfo.pageNum = 1;
      this.fetchData();
    },
    fetchDataDelay(){
      setTimeout(()=>{
        this.fetchData();
      }, 2000)
    },
    fetchData() {
      this.listLoading = true;
      const params = {
        customerId: this.customerId,
        pageNum: this.paginationInfo.pageNum,
        pageSize: this.paginationInfo.pageSize
      };
      if (this.grayControler) {
        return this.$http
          .get('/customer/linkman/list', params)
          .then(res => {
            this.contactList = res.list.map(contact => {
              this.$set(this.pending, contact.id, !!contact.isMain);
              contact.createTime = formatDate(
                safeNewDate(contact.createTime),
                'YYYY-MM-DD HH:mm:ss'
              );
              return Object.freeze(contact);
            });
            this.paginationInfo.totalItems = res.total;
          })
          .catch(err => console.error('err', err))
          .finally(() => {
            this.listLoading = false
          })
      }
      
      return getContactList(params)
        .then(res => {
          this.contactList = res.result.list.map(contact => {
            contact['customer'] = { id: contact.customerId };
            contact['remark'] = contact.remarks || '';
            contact['department'] = contact.dept || '';
            contact['productId'] = contact.esProductEntities || [];
            contact.productId.forEach(item => {
              item.label = item?.name || ''
              item.value = item?.id || ''
            })
            this.$set(this.pending, contact.id, !!contact.isMain);
            contact.createTime = formatDate(
              safeNewDate(contact.createTime),
              'YYYY-MM-DD HH:mm:ss'
            );
            return Object.freeze(contact);
          });
          this.paginationInfo.totalItems = res.result.total;
        })
        .catch(err => console.error('err', err))
        .finally(() => {
          this.listLoading = false
        })
      
    },
    buildColumns() {
      let arr = [
        {
          label: this.$t('customer.detail.customerContractTable.table.label.name'),
          field: 'name',
          show: true,
          with: '200px'
          // sortable: 'custom',
        },
        {
          label: this.$t('customer.detail.customerContractTable.table.label.department'),
          field: 'department',
          show: true
        },
        {
          label: this.$t('customer.detail.customerContractTable.table.label.from'),
          field: 'from',
          show: true,
          width: '150px'
        },
        {
          label: this.$t('customer.detail.customerContractTable.table.label.phone'),
          field: 'phone',
          show: true,
          width: '180px'
        },
        {
          label: this.$t('customer.detail.customerContractTable.table.label.email'),
          field: 'email',
          show: true,
          width: '180px'
        },
        {
          label: this.$t('customer.detail.customerContractTable.table.label.action'),
          field: 'action',
          show: this.allowEditCustomer,
          width: '120px'
        }
      ];
      if (this.grayControler) {
        arr.splice(2, 1);
      }

      return arr;
    },
    getContactList() {
      return _.cloneDeep(this.contactList)
    },
    /**
     * @description 获取联系人列表
     * -- 支持外部调用的
     */
    outsideGetContactList() {
      return this.getContactList()
    },
    // 呼叫中心来源数据
    callCenterSourceData(scope){
      return {
        sourceTypeId:scope.row.id,
        sourceType:'customer',
      }
    },
  },
  components: {
    [EditContactDialog.name]: EditContactDialog
  }
};
</script>

<style lang="scss" scoped>
.color-green {
  color: #55b7b4;
}

.customer-contact-table-container {
  padding: 16px;

  .edit-btn {
    @include text-ellipsis();
    @include fontColor();
  }

  .lm-action {
    display: flex;
    justify-content: space-between;

    .delete-contact-btn {
      color: $color-danger;
    }

    .delete-contact-btn.is-disabled,
    .delete-contact-btn.is-disabled:hover,
    .el-button.delete-contact-btn:focus {
      color: #c0c4cc;
      cursor: not-allowed;
      background-image: none;
    }
  }

  .set-default-lm-btn {
    line-height: 34px;
    display: block;
    text-align: center;
    border-radius: 3px;

    &:hover {
      cursor: pointer;
      background-color: #e7e7e7;
    }
  }
}

.custoemr-contact-name {
  display: flex;
  align-items: center;
}

.customer-linkman-name-wx {
  width: calc(100% - 50px);
}
.cur-point {
  color: $color-primary-light-6;
}
.lang-select-dropdown {
  margin-top: 0!important;
}
.del-btn {
  margin-left: -15px
}
.main-label {
  display: inline-block;
  background: rgba(255, 146, 0, 0.16);
  border-radius: 4px;
  border: 1px solid rgba(255, 146, 0, 0.16);
  color: #FF9200;
  padding: 0px 10px;
  font-size: 10px;
  height: 24px;
  line-height: 24px;
  margin: 8px 0px 8px 15px;
}
</style>
